<?php

namespace app\common\model;


use think\Cache;
use think\cache\driver\Redis;

class ResumeExecuteLog extends BaseModel
{
    /**
     *添加到记录
     * @param $params
     * @return int|string
     */
    public static function add($params){
        $company_id = $params['company_id'];
        $total_num = $params['total_num'];

        $id = self::insertGetId([
            'company_id' => $company_id,
            'total_num' => $total_num,
            'add_at' => time(),
        ]);
        return $id;
    }
    public static function edit($params){
        $id = $params['id'];
        $num = $params['num'];
        $cache_name = __METHOD__.'_'.$id;
        $cache_name_lock = __METHOD__.'lock_'.$id;
        $redis = new Redis();
        while (true){
//            dolog('lock',[$redis->get($cache_name_lock),microtime(1)]);
            if($redis->setnx($cache_name_lock,1)){
                break;
            }
            usleep(100000);
            continue;
        }
        $total_num = $redis->get($cache_name);
//        dolog('$total_num',[$total_num,microtime(1)]);
        if($total_num){
            $total_num += $num;
        }else{
            $total_num = $num;
        }
        $redis->set($cache_name,$total_num);
        $redis->rm($cache_name_lock);
//        dolog('Redis Num',$total_num);
        $res = self::where('id',$id)->where('completed_at',0)->field('total_num,completed_num')->find();
        if(!$res){
            return false;
        }
        $update_num = $total_num;
        $data = [
            'completed_num' => $update_num
        ];
        if($res['total_num'] <= $total_num){
            $data['completed_at'] = time();
            $redis->rm($cache_name);
        }
        $res = self::where('id',$id)->update($data);
        dolog('$params',[$params,$res]);
        // 删除记录数据
        $unique_key = $params['unique_key']??($id.'_0');
        $model = ResumeExecuteLogItems::where('unique_key',$unique_key);
        $model->count() && ResumeExecuteLogItems::where('unique_key',$unique_key)->delete();

        return true;
    }
}
